import com.alibaba.fastjson.JSONObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class Mongo {
    private MongoClient client;
    private MongoCollection<Document> collection;
    private String collectionName;

    public Mongo(String host, int port, String databaseName, String collectionName, String username, String password) {
        this.collectionName = collectionName;
        ServerAddress address = new ServerAddress(host, port);
        MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
        client = new MongoClient(address, credential, MongoClientOptions.builder().build());
        MongoDatabase database = client.getDatabase(databaseName);
        collection = database.getCollection(collectionName);
    }

    public void close() {
        client.close();
    }

    public boolean contains(String _id) {
        return collection.find(new Document("_id", _id)).iterator().hasNext();
    }

    public void insertOne(String _id, JSONObject object) {
        if (contains(_id)) {
            Log4M.e(collectionName, "insert one failed. dup id: " + _id);
            return;
        }
        object.put("_id", _id);
        collection.insertOne(new Document(object));
        Log4M.i(collectionName, "insert one successfully. id: " + _id);
    }

    public void replaceOne(String _id, JSONObject object) {
        object.put("_id", _id);
        if (contains(_id)) {
            collection.replaceOne(new Document("_id", _id), new Document(object));
            Log4M.i(collectionName, "replace one successfully. id: " + _id);
            return;
        }
        collection.insertOne(new Document(object));
        Log4M.i(collectionName, "insert one successfully. id: " + _id);
    }

    public long count() {
        return collection.countDocuments();
    }

}

class Log4M {

    public static void i(String tag, String msg) {
        System.out.println(String.format("[%-13s] [%-7s] %s", tag, "INFO", msg));
    }

    public static void e(String tag, String msg) {
        System.out.println(String.format("[%-13s] \u001b[31m[%-7s] %s\u001b[0m", tag, "ERROR", msg));
    }

    public static void w(String tag, String msg) {
        System.out.println(String.format("[%-13s] \u001b[33m[%-7s] %s\u001b[0m", tag, "WARNING", msg));
    }
}